import React from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Popconfirm } from 'antd';
import { formatMessage } from 'umi';
import produce from 'immer';
import Icon from '@/zero/components/Icon';
import DrawerForm from '@/zero/components/Ext/Forms/DMForm/DrawerForm';
import SimpleTable from '@/zero/components/Table/Ext/SimpleTable';
import styles from './index.less';

const Index = (props) => {
  const {
    rowKey = 'key',
    sortIndexKey = 'sortIndex',

    columns = [],
    actionColumn = {},
    items = [],

    value = [],
    onChange,

    disabled = false,
    disabledExcludes = [],
    actionsAddonBefore,
    actionsAddonAfter,

    // eslint-disable-next-line
    beforeOk = (newRecord, newValue, actionType, { resolve, reject }) => {
      resolve();
    },

    hideCreate = false, // 隐藏新增按钮 => boolean
    createTemplate = {},
    onCreate,

    hideUpdate = false, // 隐藏修改按钮 => boolean || function
    hideUpdate2Disabled = true,
    onUpdate,

    hideDelete = false, // 隐藏删除按钮 => boolean || function
    hideDelete2Disabled = true,
    onDelete,

    drawerProps,

    ...rest
  } = props;

  const newDrawerProps = {
    defaultRowLayout: {
      gutter: 16,
    },
    defaultColLayout: {
      span: 24,
    },
    width: 'auto',
    height: 'auto',
    ...drawerProps,
  };

  const newValue =
    value?.map((item, index) => ({
      ...item,
      key: item[rowKey] || item.key || item.id,
      [sortIndexKey]: index + 1,
    })) || [];

  const newColumns = produce(columns, (draftState) => {
    if (!disabled || disabledExcludes.length) {
      draftState.push({
        title: formatMessage({ id: '操作' }),
        dataIndex: 'x-action',
        render: (text, record, index) => (
          <>
            {(!disabled || disabledExcludes.includes('actionsAddonBefore')) &&
              (typeof actionsAddonBefore === 'function'
                ? actionsAddonBefore(record, index)
                : actionsAddonBefore)}

            {!disabled &&
              (hideUpdate === false ||
              (typeof hideUpdate === 'function' && !hideUpdate(record, index)) ? (
                <DrawerForm
                  {...newDrawerProps}
                  title={formatMessage({ id: '修改' })}
                  items={items}
                  initialValue={record}
                  onOk={(newRecord, success) => {
                    const finalRecord = {
                      ...record,
                      ...newRecord,
                    };
                    new Promise((resolve, reject) => {
                      beforeOk(finalRecord, newValue, 'update', { resolve, reject });
                    }).then(() => {
                      if (onChange) {
                        onChange(
                          newValue.map((item) => {
                            if (item.key === finalRecord.key) {
                              return finalRecord;
                            }
                            return item;
                          }),
                        );
                        if (onUpdate) {
                          onUpdate(finalRecord, index);
                        }
                        success();
                      }
                    });
                  }}
                >
                  <a>
                    <Icon type="icon-xiugai07" />
                  </a>
                </DrawerForm>
              ) : (
                hideUpdate2Disabled && (
                  <a>
                    <Icon type="icon-xiugai07" style={{ color: '#00000040' }} />
                  </a>
                )
              ))}

            {!disabled &&
              (hideDelete === false ||
              (typeof hideDelete === 'function' && !hideDelete(record, index)) ? (
                <>
                  &nbsp;&nbsp;&nbsp;
                  <Popconfirm
                    title={formatMessage({ id: '删除提示' })}
                    onConfirm={() => {
                      new Promise((resolve, reject) => {
                        beforeOk(record, newValue, 'delete', { resolve, reject });
                      }).then(() => {
                        if (onChange) {
                          onChange(newValue.filter((item) => item.key !== record.key));
                          if (onDelete) {
                            onDelete(record, index);
                          }
                        }
                      });
                    }}
                  >
                    <a>
                      <Icon type="icon-shanchu2" />
                    </a>
                  </Popconfirm>
                </>
              ) : (
                hideDelete2Disabled && (
                  <>
                    &nbsp;&nbsp;&nbsp;
                    <a>
                      <Icon type="icon-shanchu2" style={{ color: '#00000040' }} />
                    </a>
                  </>
                )
              ))}

            {(!disabled || disabledExcludes.includes('actionsAddonAfter')) &&
              (typeof actionsAddonAfter === 'function'
                ? actionsAddonAfter(record, index)
                : actionsAddonAfter)}
          </>
        ),
        ...actionColumn,
      });
    }
    return draftState;
  });

  return (
    <span className={styles.col24}>
      <SimpleTable
        pagination={false}
        {...rest}
        rowKey={rowKey}
        columns={newColumns}
        dataSource={newValue}
        footer={
          !disabled &&
          !hideCreate &&
          (() => (
            <DrawerForm
              {...newDrawerProps}
              title={formatMessage({ id: '新增' })}
              items={items}
              initialValue={createTemplate}
              onOk={(newRecord, success) => {
                new Promise((resolve, reject) => {
                  beforeOk(newRecord, newValue, 'create', { resolve, reject });
                }).then(() => {
                  if (onChange) {
                    const newKey = Date.now();
                    const finalRecord = {
                      key: newKey,
                      [rowKey]: newKey,
                      [sortIndexKey]: newValue.length + 1,
                      ...newRecord,
                    };
                    onChange(newValue.concat(finalRecord));
                    if (onCreate) {
                      onCreate(finalRecord);
                    }
                    success();
                  }
                });
              }}
            >
              <Button style={{ width: '100%' }} type="dashed" icon={<PlusOutlined />}>
                {formatMessage({ id: '新增' })}
              </Button>
            </DrawerForm>
          ))
        }
      />
    </span>
  );
};

Index.displayName = 'TableForm';
export default Index;
